import { getAIResponse } from '../../utils/ai-service';

Page({
  data: {
    messages: [],
    inputValue: '',
    statusBarHeight: 0,
    // 状态管理
    isLoading: false
  },

  async onLoad() {
    try {
      // 获取系统信息
      const res = await wx.getSystemInfo();
      this.setData({
        statusBarHeight: res.statusBarHeight
      });
    } catch (err) {
      console.error('获取系统信息失败', err);
    }
  },

  // 输入框变化
  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  // 发送消息
  async sendMessage() {
    const content = this.data.inputValue.trim();
    if (!content) return;
    
    // 添加用户消息
    const userMessage = {
      role: 'user',
      content,
      time: new Date().toLocaleTimeString(),
      id: Date.now().toString()
    };
    
    this.setData({
      messages: [...this.data.messages, userMessage],
      inputValue: '',
      isLoading: true
    });

    try {
      // 调用AI服务
      const aiResponse = await getAIResponse(content);
      const aiMessage = {
        role: 'assistant',
        content: aiResponse,
        time: new Date().toLocaleTimeString(),
        id: (Date.now() + 1).toString()
      };

      // 更新消息列表
      this.setData({
        messages: [...this.data.messages, aiMessage],
        isLoading: false
      });
    } catch (error) {
      console.error('AI请求失败', error);
      this.setData({
        isLoading: false
      });
      wx.showToast({
        title: '请求失败，请重试',
        icon: 'error'
      });
    }
  },

  // 处理点击提示问题
  askQuestion(e) {
    const question = e.currentTarget.dataset.question;
    this.setData({
      inputValue: question
    }, () => {
      this.sendMessage();
    });
  }
});